# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from django.shortcuts import render_to_response,render, get_object_or_404
from django.core.urlresolvers import reverse
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    #template = loader.get_template('.\\polls\\index.html')
    context = Context({
        'latest_poll_list': latest_poll_list,
    })
    #return HttpResponse(template.render(context))
    #return render_to_response('.\\polls\\index.html',{})
    return render(request,'./polls/index1.html',context)


def detail(request, poll_id):
    poll = get_object_or_404(Poll,pk = poll_id)
    return render(request, './polls/detail.html', {'poll':poll})

def results(request, poll_id):
    poll = get_object_or_404(Poll,pk = poll_id)
    return render(request, './polls/results.html', {'poll':poll})

def vote(request, poll_id):
    poll = get_object_or_404(Poll,pk = poll_id)
    try:
        selected_choice = poll.choice_set.get(pk = request.POST['choice'])
    except (KeyError, Choice.DoesNoExist):
        return render(request, './polls/detail.html',{'poll':poll})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results',args = (poll.id,)))
